import type { FixedLengthArray } from "@utils";

export const colorArray = (
  color: string,
  opacity: number = 1
): FixedLengthArray<number, 4> => {
  const hex = color[0] == "#" ? color.replace("#", "") : color;
  let r = 0,
    g = 0,
    b = 0,
    a = opacity;
  if (hex.length == 3) {
    r = Number(
      (parseInt("0x" + hex.slice(0, 1) + hex.slice(0, 1)) / 255).toFixed(2)
    );
    g = Number(
      (parseInt("0x" + hex.slice(1, 2) + hex.slice(1, 2)) / 255).toFixed(2)
    );
    b = Number(
      (parseInt("0x" + hex.slice(2, 3) + hex.slice(2, 3)) / 255).toFixed(2)
    );
    return [r, g, b, a];
  }
  if (hex.length == 4) {
    r = Number(
      (parseInt("0x" + hex.slice(0, 1) + hex.slice(0, 1)) / 255).toFixed(2)
    );
    g = Number(
      (parseInt("0x" + hex.slice(1, 2) + hex.slice(1, 2)) / 255).toFixed(2)
    );
    b = Number(
      (parseInt("0x" + hex.slice(2, 3) + hex.slice(2, 3)) / 255).toFixed(2)
    );
    a = Number(
      (parseInt("0x" + hex.slice(3, 4) + hex.slice(3, 4)) / 255).toFixed(2)
    );
    return [r, g, b, a];
  }
  if (hex.length == 5) {
    r = Number(
      (parseInt("0x" + hex.slice(0, 1) + hex.slice(0, 1)) / 255).toFixed(2)
    );
    g = Number(
      (parseInt("0x" + hex.slice(1, 2) + hex.slice(1, 2)) / 255).toFixed(2)
    );
    b = Number(
      (parseInt("0x" + hex.slice(2, 3) + hex.slice(2, 3)) / 255).toFixed(2)
    );
    a = Number((parseInt("0x" + hex.slice(3, 5)) / 255).toFixed(2));
    return [r, g, b, a];
  }
  if (hex.length == 6) {
    r = Number((parseInt("0x" + hex.slice(0, 2)) / 255).toFixed(2));
    g = Number((parseInt("0x" + hex.slice(2, 4)) / 255).toFixed(2));
    b = Number((parseInt("0x" + hex.slice(4, 6)) / 255).toFixed(2));
    return [r, g, b, a];
  }
  if (hex.length == 8) {
    r = Number((parseInt("0x" + hex.slice(0, 2)) / 255).toFixed(2));
    g = Number((parseInt("0x" + hex.slice(2, 4)) / 255).toFixed(2));
    b = Number((parseInt("0x" + hex.slice(4, 6)) / 255).toFixed(2));
    a = Number((parseInt("0x" + hex.slice(6, 8)) / 255).toFixed(2));
    return [r, g, b, a];
  }
  return [1, 1, 1, a];
};
